class UserManager {

    constructor(socket, serverType) {
        console.log('初始化');
        this.id = socket.id;
        this.socket = socket;
        this.serverType = serverType;
        this.name = null;
        this.number = 0;
        this.rightAnswer = []; //回答正确的题目.
        this.errAnswer = []; //回答错误.
    }
    //登录
    setName(name) {
        if (this.name != null) {
            this.socket.emit('msg', sendObj('login', 1, '你已经登录过了'));
            return;
        }

        if (this.serverType.type == 1) {
            this.socket.emit('msg', sendObj('login', 1, '答题已经开始了'));
            return;
        }

        console.log('登录' + this.socket.id + ',登录名:' + name);
        this.name = name;

        this.socket.emit('msg', sendObj('login', 0, name));
    }

    //答题
    setAnswer(value) {
        var question = this.serverType.nowQuestion;
        console.log(JSON.stringify(this.serverType.nowQuestion));
        if (question == null) {
            this.socket.emit('msg', sendObj('answer', 0, '还没开始答题'));
        } else if (question.rightAnswer == value) {
            this.number++;
            this.rightAnswer.push(question);
        } else {
            this.errAnswer.push(question);
        }
    }


    //只做监听.
    listen() {
        this.socket.on('msg', strText => {
            //console.log('客户端消息接收:' + data);
            var data = JSON.parse(strText); //解析json
            this.action(data);
        });
    }

    //消息分发.
    action(data) {
        switch (data.type) {
            case 'login':
                this.setName(data.value);
                break;
            case 'answer':
                this.setAnswer(data.value);
                break;
            default:
                break;
        }
    }

}

function sendObj(type, success, data) {
    var obj = {
        type: type,
        success: success,
        data: data
    }
    return JSON.stringify(obj);
}





module.exports = UserManager;